// pages/pointsShopOrder/pointsShopOrder.js
const app = getApp()
const { getUserAllOrders, cancelUserOrder } = require("../../utils/api");
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    header: {
      title: '订单',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight
    },

    active: 2,
    isPoup: false,
    list: ['新品', '周转', '维护'],
    userInfo: null,
    allOrder: [],
    navigation:[
      { 
        checked: true,
        name:"全部",
        id:"0"
      },
      {
        checked: false,
        name:"代发货",
        id:"1"
      },
      {
        checked: false,
        name:"已完成",
        id:"2"
      },
      {
        checked: false,
        name:"已取消",
        id:"3"
      }
    ],
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  handelback(){
    wx.switchTab({
      url: '/pages/mine/mine',
    })
  },
  cancel(e) {
    const index = e.currentTarget.dataset.value;
    const data = { PhoneNumber: this.data.userInfo.phoneNumber, 
      OrderNumber: this.data.allOrder[index].orderNumber,
    };
    const path = 'this.data.allOrder['+index+'].status'
    const allOrder = this.data.allOrder;
    cancelUserOrder(data).then(res =>{
      if (res.code == 4006030) {
        allOrder.splice(index, 1)
        this.setData({
          isPoup: true,
          allOrder: allOrder,
          path: '已取消'
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    });
  },

  navigationChange(e){
    const index =  e.detail.index
    const navigation = this.data.navigation.map((item, idx) => ({
      ...item,
      checked: idx === index
    }));
    const updatedOrders = this.data.allOrder.map(item => {
      return {
        ...item,
        show: item.status === this.data.navigation[index].name || this.data.navigation[index].name === '全部'
      };
    });
    this.setData({ navigation, allOrder: updatedOrders });
  },

  closeBox() {
    this.setData({
      isPoup: false
    })
  },
  close() {
    this.setData({
      isPoup: false
    })
  },
  onLoad(options) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
  },

  onPageScroll(e) {
    this.setData({
      isBg: e.scrollTop < 40 ? false : true
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const data = { PhoneNumber: this.data.userInfo.phoneNumber };
    getUserAllOrders(data).then(res => {
      if (res.code == 4006020) {
        const updatedData = res.data.map(item => ({
          ...item, // 复制当前对象的所有属性
          show: true // 添加 Show 属性，默认值为 true
        }));
        this.setData({
          allOrder: updatedData
        })
      }
    })
  },
})